//
//  DCControlViewController.m
//  cangoe
//
//  Created by 魏延(颜魏) on 2025/2/18.
//

#import "DCControlViewController.h"
#import "ProgressHUD.h"
#import "BTManager.h"

@interface DCControlViewController ()

@property (weak, nonatomic) IBOutlet UIButton *swBtn1;
@property (weak, nonatomic) IBOutlet UIButton *swBtn11;
@property (weak, nonatomic) IBOutlet UIButton *swBtn2;
@property (weak, nonatomic) IBOutlet UIButton *swBtn22;
@property (weak, nonatomic) IBOutlet UIButton *swBtn3;
@property (weak, nonatomic) IBOutlet UIButton *swBtn33;
@property (weak, nonatomic) IBOutlet UIButton *swBtn4;
@property (weak, nonatomic) IBOutlet UIButton *swBtn44;
@property (weak, nonatomic) IBOutlet UIView *swView3;
@property (weak, nonatomic) IBOutlet UIView *swView4;

@property (weak, nonatomic) IBOutlet UILabel *vtLabel;
@property (weak, nonatomic) IBOutlet UILabel *stLabel;

@property (weak, nonatomic) IBOutlet UIView *voltageStepView;
@property (weak, nonatomic) IBOutlet UILabel *voltageStepLabel;
@property (weak, nonatomic) IBOutlet UIView *voltageListView;

@property (weak, nonatomic) IBOutlet UIView *voltageView;
@property (weak, nonatomic) IBOutlet UILabel *voltageLabel;

@property (weak, nonatomic) IBOutlet UIView *timeView;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UIView *timeListView;

@property (weak, nonatomic) IBOutlet UIView *bgView;
@property (weak, nonatomic) IBOutlet UIView *tipsView1;
@property (weak, nonatomic) IBOutlet UIView *tipsView2;
@property (weak, nonatomic) IBOutlet UIView *tipsView3;

@property (strong, nonatomic) NSTimer *timer;
@property (assign, nonatomic) NSInteger queryOrder;
@property (assign, nonatomic) BOOL isWrite;
@property (strong, nonatomic) NSMutableArray *voltageStepList;
@property (strong, nonatomic) NSMutableArray *timeStepList;
@property (assign, nonatomic) NSInteger voltageIndex;
@property (assign, nonatomic) NSInteger timeIndex;
@property (assign, nonatomic) BOOL isKbShow;
@property (assign, nonatomic) BOOL swBtn33State;

@end

@implementation DCControlViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.timer invalidate];
    self.timer = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.voltageStepList = [[NSMutableArray alloc] init];
    self.timeStepList = [[NSMutableArray alloc] init];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReciveData:) name:kBTDidReciveData object:nil];

    self.swBtn1.layer.cornerRadius = 6;
    self.swBtn1.layer.masksToBounds = YES;

    self.swBtn2.layer.cornerRadius = 6;
    self.swBtn2.layer.masksToBounds = YES;
    
    self.voltageStepView.layer.cornerRadius = 6;
    self.voltageStepView.layer.masksToBounds = YES;
    self.voltageStepView.layer.borderColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.3].CGColor;
    self.voltageStepView.layer.borderWidth = 1;

    self.voltageListView.layer.cornerRadius = 6;
    self.voltageListView.layer.masksToBounds = YES;
    self.voltageListView.layer.borderColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.3].CGColor;
    self.voltageListView.layer.borderWidth = 1;

    self.voltageView.layer.cornerRadius = 6;
    self.voltageView.layer.masksToBounds = YES;
    self.voltageView.layer.borderColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.3].CGColor;
    self.voltageView.layer.borderWidth = 1;

    self.timeView.layer.cornerRadius = 6;
    self.timeView.layer.masksToBounds = YES;
    self.timeView.layer.borderColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.3].CGColor;
    self.timeView.layer.borderWidth = 1;

    self.timeListView.layer.cornerRadius = 6;
    self.timeListView.layer.masksToBounds = YES;
    self.timeListView.layer.borderColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.3].CGColor;
    self.timeListView.layer.borderWidth = 1;

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTap:)];
    [self.bgView addGestureRecognizer:tap];

    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTap1:)];
    [self.voltageStepView addGestureRecognizer:tap1];

    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTap2:)];
    [self.timeView addGestureRecognizer:tap2];
    
    [self beginQuery];
    
    // 监听键盘弹起
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    // 监听键盘收起
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

- (void)keyboardWillShow:(NSNotification *)notification {
    self.isKbShow = YES;
}

- (void)keyboardWillHide:(NSNotification *)notification {
    self.isKbShow = NO;
}

- (void)beginQuery {
    [self queryVoltageStep];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self querySwStatus];
    });
//    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
//        if (self.isWrite || self.isKbShow) {
//            return;
//        }
//        switch (self.queryOrder) {
//            case 0:
//                [self queryVoltageStep];
//                break;
//            case 1:
//                [self querySwStatus];
//                break;
//            default:
//                break;
//        }
//        self.queryOrder ++;
//        if (self.queryOrder>5) {
//            self.queryOrder = 0;
//        }
//    }];
}

- (void)handleTap:(UITapGestureRecognizer *)tap {
    self.bgView.hidden = YES;
    self.tipsView1.hidden = YES;
    self.tipsView2.hidden = YES;
    self.tipsView3.hidden = YES;
    self.voltageListView.hidden = YES;
    self.timeListView.hidden = YES;
}

- (void)handleTap1:(UITapGestureRecognizer *)tap {
    self.bgView.hidden = NO;
    self.voltageListView.hidden = NO;
}

- (void)handleTap2:(UITapGestureRecognizer *)tap {
    self.bgView.hidden = NO;
    self.timeListView.hidden = NO;
}

- (IBAction)actionBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)actionTips1:(id)sender {
    self.bgView.hidden = NO;
    self.tipsView1.hidden = NO;
}

- (IBAction)actionTips2:(id)sender {
    self.bgView.hidden = NO;
    self.tipsView2.hidden = NO;
}

- (IBAction)actionTips3:(id)sender {
    self.bgView.hidden = NO;
    self.tipsView3.hidden = NO;
}

- (IBAction)actionCancel:(id)sender {
    self.bgView.hidden = YES;
    self.voltageListView.hidden = YES;
}

- (IBAction)actionVoltageStep:(UIButton *)sender {
    self.voltageIndex = sender.tag - 100;
    self.bgView.hidden = YES;
    self.voltageListView.hidden = YES;
    self.voltageStepLabel.text = sender.titleLabel.text;
    [self actionSet1:[UIButton new]];
}

- (IBAction)actionTimeStep:(UIButton *)sender {
    self.timeIndex = sender.tag - 1000;
    self.bgView.hidden = YES;
    self.timeListView.hidden = YES;
    self.timeLabel.text = sender.titleLabel.text;
    [self actionSet2:[UIButton new]];
}

- (IBAction)actionSet1:(id)sender {
    if (self.swBtn33State) {
        return;
    }
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Confirm" message:@"Are you sure you want to write to the device?" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"Confirm" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self setVoltageOrder:self.voltageIndex];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alertController animated:true completion:nil];
}

- (IBAction)actionSet2:(id)sender {
    if (self.swBtn33State) {
        return;
    }
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Confirm" message:@"Are you sure you want to write to the device?" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"Confirm" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self setTimerOrder:self.timeIndex];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alertController animated:true completion:nil];
}

- (IBAction)actionSet3:(id)sender {
}

- (IBAction)actionSet4:(id)sender {
}

- (void)didReciveData:(NSNotification *)notification {
    if (self.isKbShow) {
        return;
    }
    NSData *reciveData = notification.object;
    Byte *receieveData = (Byte*)reciveData.bytes;
    if (receieveData[2] == 0x3c) {
        self.voltageIndex = receieveData[3] * 256 + receieveData[4];
        [self.voltageStepList removeAllObjects];
        for (NSInteger i=0; i<7; i++) {
            CGFloat onV = (receieveData[5 + 4 * i] * 256 + receieveData[6 + 4 * i]) / 10.0;
            CGFloat offV = (receieveData[7 + 4 * i] * 256 + receieveData[8 + 4 * i]) / 10.0;
            [self.voltageStepList addObject:[NSString stringWithFormat:@"    ON - %.1fV, OFF - %.1fV", onV, offV]];
        }
        for (NSInteger i=0; i<self.voltageStepList.count; i++) {
            UIButton *btn = [self.view viewWithTag:100 + i];
            [btn setTitle:self.voltageStepList[i] forState:UIControlStateNormal];
            btn.selected = self.voltageIndex == i;
        }
        self.voltageStepLabel.text = self.voltageStepList[self.voltageIndex >= self.voltageStepList.count ? 0 : self.voltageIndex];

        self.timeIndex = receieveData[5 + 4 * 7] * 256 + receieveData[6 + 4 * 7];
        [self.timeStepList removeAllObjects];
        for (NSInteger i=0; i<7; i++) {
            NSInteger onTime = receieveData[7 + 4 * (7 + i)] * 256 + receieveData[8 + 4 * (7 + i)];
            NSInteger offTime = receieveData[9 + 4 * (7 + i)] * 256 + receieveData[10 + 4 * (7 + i)];
            [self.timeStepList addObject:[NSString stringWithFormat:@"ON - %@ %@, OFF - %@ %@", onTime >= 60 ? [NSString stringWithFormat:@"%.1f", onTime / 60.0] : @(onTime), onTime < 60 ? @"Sec" : @"Minute", offTime >= 60 ? [NSString stringWithFormat:@"%.1f", offTime / 60.0] : @(offTime), offTime < 60 ? @"Sec" : @"Minute"]];
        }
        for (NSInteger i=0; i<self.timeStepList.count; i++) {
            UIButton *btn = [self.view viewWithTag:1000 + i];
            [btn setTitle:self.timeStepList[i] forState:UIControlStateNormal];
        }
        self.timeLabel.text = self.timeStepList[self.timeIndex >= self.timeStepList.count ? 0 : self.timeIndex];
    }else if (receieveData[2] == 0x04) {
         BOOL isselect = (receieveData[3] * 256 + receieveData[4]) & 0x01;
//        [self.swBtn3 setImage:[UIImage imageNamed:isselect ? @"sw_on" : @"sw_off"] forState:UIControlStateNormal];
        self.swView3.backgroundColor = isselect ? RGB16(0xFF2D00) : RGB16(0xa3a3a3);
        [self.swBtn33 setTitle:isselect ? @"ON" : @"OFF" forState:UIControlStateNormal];
        self.swBtn33State = isselect;
        BOOL isselect1 = (receieveData[3] * 256 + receieveData[4]) & 0x02;
//        [self.swBtn4 setImage:[UIImage imageNamed:isselect1 ? @"sw_on" : @"sw_off"] forState:UIControlStateNormal];
        [self.swBtn44 setTitle:isselect1 ? @"ON" : @"OFF" forState:UIControlStateNormal];
        self.swView4.backgroundColor = isselect1 ? RGB16(0xFF2D00) : RGB16(0xa3a3a3);
        self.voltageLabel.text = [NSString stringWithFormat:@"%.1f", (receieveData[5] * 256 + receieveData[6]) / 10.0];
    }else if (receieveData[2] == 0x25) {
        self.isWrite = NO;
        UIButton *btn = [self.view viewWithTag:1000 + self.voltageIndex];
        btn.selected = YES;
        [ProgressHUD showSuccessMessage:@"Parameter setting succeeded"];
    }
}

- (void)setVoltageOrder:(NSInteger)index {
    self.isWrite = YES;
    Byte bytes[11];
    bytes[0] = 0x01;
    bytes[1] = 0x10;
    bytes[2] = 0x25;
    bytes[3] = 0x00;
    bytes[4] = 0x00;
    bytes[5] = 0x01;
    bytes[6] = 0x02;
    bytes[7] = 0x00;
    bytes[8] = index;
    bytes[9] = 0x00;
    bytes[10] = 0x00;
    [[BTManager sharedBTManager] sendCommandWithCrc:bytes length:11];
}

- (void)setTimerOrder:(NSInteger)index {
    self.isWrite = YES;
    Byte bytes[11];
    bytes[0] = 0x01;
    bytes[1] = 0x10;
    bytes[2] = 0x25;
    bytes[3] = 0x01;
    bytes[4] = 0x00;
    bytes[5] = 0x01;
    bytes[6] = 0x02;
    bytes[7] = 0x00;
    bytes[8] = index;
    bytes[9] = 0x00;
    bytes[10] = 0x00;
    [[BTManager sharedBTManager] sendCommandWithCrc:bytes length:11];
}

- (void)queryVoltageStep {
    Byte bytes[8];
    bytes[0] = 0x01;
    bytes[1] = 0x03;
    bytes[2] = 0x25;
    bytes[3] = 0x06;
    bytes[4] = 0x00;
    bytes[5] = 0x1e;
    bytes[6] = 0x00;
    bytes[7] = 0x00;
    [[BTManager sharedBTManager] sendCommandWithCrc:bytes length:8];
}

- (void)querySwStatus {
    Byte bytes[8];
    bytes[0] = 0x01;
    bytes[1] = 0x03;
    bytes[2] = 0x25;
    bytes[3] = 0x24;
    bytes[4] = 0x00;
    bytes[5] = 0x02;
    bytes[6] = 0x00;
    bytes[7] = 0x00;
    [[BTManager sharedBTManager] sendCommandWithCrc:bytes length:8];
}

@end
